package com.example.web.websystem.service;

import com.example.web.websystem.dao.SysAdministratorSettingDao;
import com.example.web.websystem.dao.SysUserDao;
import com.example.web.websystem.dao.model.SysRoleDO;
import com.example.web.websystem.dao.model.SysUserDO;
import com.example.web.websystem.response.BusinessError;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by YangGang on 2021/1/20 15:21。
 */
@Service
public class SysUserService {
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysAdministratorSettingService sysAdministratorSettingService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysGroupService sysGroupService;

    public SysUserDO getSysUserByUsernamePassword(String username, String password) {
        return sysUserDao.selectByUsernamePassword(username, password);
    }

    public SysUserDO getSysUserByUserId(long userId) {
        return sysUserDao.selectByPrimaryKey(userId);
    }

    public List<SysUserDO> listSysUsersByGroupId(long groupId) {
        return sysUserDao.listByGroupId(groupId);
    }

    public List<SysUserDO> listNormalSysUsers() {
        return sysUserDao.listNormal();
    }

    public List<SysUserDO> listAllSysUsers() {
        return sysUserDao.listAll();
    }


    @Transactional
    public int addSysUser(SysUserDO sysUser) {
        sysUser.setUserId(null);
        int add = sysUserDao.insertSelective(sysUser);
        if (add != 1) throw new BusinessError("添加用户失败");
        return add;
    }

    @Transactional
    public int updateSysUser(SysUserDO sysUser) {
        int up = sysUserDao.updateByPrimaryKeySelective(sysUser);
        if (up != 1) throw new BusinessError("更新用户信息失败");
        return up;
    }

    /**
     * 删除-用户：逻辑删除
     *
     * @param userId
     * @return
     */
    @Transactional
    public int deleteSysUser(long userId) {
        SysUserDO sysUser = new SysUserDO();
        sysUser.setUserId(userId);
        sysUser.setIsDeleted(true);
        int up = sysUserDao.updateByPrimaryKeySelective(sysUser);
        if (up != 1) throw new BusinessError("删除用户失败");
        return up;
    }

    /**
     * 修改-组织所有用户的删除状态
     *
     * @param groupId
     */
    @Transactional
    public int updateSysUserIsDeletedByGroupId(long groupId, boolean isDeleted) {
        return sysUserDao.updateIsDeletedByGroupId(groupId, isDeleted);
    }

    /**
     * 查询-用户的paths列表
     * 1，管理员菜单
     * 2，普通用户菜单
     *
     * @param userId
     * @param groupId
     * @param isAdministrator
     * @return
     */
    public Set<String> listSysUserPaths(long userId, Long groupId, Boolean isAdministrator) {
        if (isAdministrator) {
            return Stream.of(sysAdministratorSettingService.getAdministratorSetting().getAdministratorPaths().split(","))
                    .distinct().collect(Collectors.toSet());
        } else {
            String openPaths = sysAdministratorSettingService.getAdministratorSetting().getOpenPaths();
            String groupPaths = sysGroupService.getSysGroup(groupId).getGroupPaths();
            List<SysRoleDO> sysRoleDOList = sysRoleService.listSysRoleByUserId(userId);
            StringBuffer sb = new StringBuffer();
            sysRoleDOList.forEach(x -> {
                sb.append(x.getRolePaths());
                sb.append(",");
            });
            String rolePaths = sb.substring(0, sb.length() - 1);
            if ("*".equals(rolePaths)) rolePaths = groupPaths;
            if ("*".equals(openPaths) && "*".equals(groupPaths)) {
                return Stream.of(rolePaths.split(",")).distinct().collect(Collectors.toSet());
            } else if ("*".equals(openPaths)) {
                Set<String> groupSet = Stream.of(groupPaths.split(",")).distinct().collect(Collectors.toSet());
                return Stream.of(rolePaths.split(",")).distinct().filter(x -> "*".equals(x) || groupSet.contains(x)).collect(Collectors.toSet());
            } else if ("*".equals(groupPaths)) {
                Set<String> openSet = Stream.of(openPaths.split(",")).distinct().collect(Collectors.toSet());
                return Stream.of(rolePaths.split(",")).distinct().filter(x -> "*".equals(x) || openSet.contains(x)).collect(Collectors.toSet());
            } else {
                Set<String> groupSet = Stream.of(groupPaths.split(",")).distinct().collect(Collectors.toSet());
                Set<String> openSet = Stream.of(openPaths.split(",")).distinct().collect(Collectors.toSet());
                return Stream.of(rolePaths.split(",")).distinct()
                        .filter(x -> "*".equals(x) || (groupSet.contains(x) && openSet.contains(x))).collect(Collectors.toSet());
            }
        }
    }

    /**
     * 修改-用户的roleIds
     *
     * @param userId
     * @param roleIds
     * @return
     */
    @Transactional
    public int updateSysUserRoleIds(long userId, String roleIds) {
        SysUserDO sysUser = new SysUserDO();
        sysUser.setUserId(userId);
        sysUser.setRoleIds(roleIds);
        int up = sysUserDao.updateByPrimaryKeySelective(sysUser);
        if (up != 1) throw new BusinessError("修改用户角色失败");
        return up;

    }


}
